package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.*;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private  UserMapper userMapper;
    //发送短信
    @Override
    public void sendMsg(String phone) {
        //1.生成6位随机数验证码
        String code = RandomUtil.randomNumbers(6);
        code = "123";  //TODO 先写死咯
        //2.调用阿里云sms发送短信
//        smsTemplate.sendSms(phone,code); //TODO 开发期间不发送短信
        //3.像redis存储验证码五分钟
        redisTemplate.opsForValue().set("code"+phone,code, Duration.ofSeconds(300));
    }


    //用户登录
    @Override
    public ResultInfo login(String phone, String code) {
        //1.校验验证码  前端用户输入--redis存储
        //取出redis中验证码
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code" + phone);

        //比较 不一致登陆失败
        if (!StrUtil.equals(code,codeFromRedis)){
            throw new CustomException("验证码不正确！");
        }

        //2.根据手机号查询数据库
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        User user = userMapper.selectOne(qw);
        if (user == null ){
            //新用户 注册
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }else {
            //老用户 登录
            if (user.getStatus() != 1){
                throw  new CustomException("您的账户已被冻结，请联系商家处理！");
            }
        }

        //jwt制作token
        Map claims = new HashMap();
        claims.put("id",user.getId());
        claims.put("phone",user.getPhone());
        String token = JwtUtil.createToken(claims);

        //redis存储user对象（敏感，有效期）
        redisTemplate.opsForValue().set("phone:"+user.getPhone(),user,Duration.ofDays(1));

        //清理redis验证码（安全性）
        redisTemplate.delete("code:" + phone);

        //返回token
        return ResultInfo.success(token);
    }

    //退出登录
    @Override
    public void logout() {
        redisTemplate.delete("phone:" + UserHolder.get().getPhone());
    }
}
